package com.my.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.my.dao.DAO;
import com.my.dao.impl.DAOImpl;
import com.my.entity.User;

public class UserController {
	
	String pwd = "a";
	DAO dao = new DAOImpl();
	
	public void login(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		try {
			PrintWriter writer = response.getWriter();
			String name = request.getParameter("name");
			String pwd = request.getParameter("pwd");
			String hql = "from User u where u.name = ?";
			List<User> users = dao.queryByHQL(hql, name);
			if(users == null || users.isEmpty()) {
				writer.println("用户不存在");
			} else {
				User u = users.get(0);
				if(this.pwd.equals(pwd)) {
					session.setAttribute("loginUser", u);
					writer.println("用户" + name + "登录成功");
				} else {
					writer.println("密码不正确");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void index(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("UserController.index()");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println("index");
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("UserController.add()");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println("add");
	}
}
